package dao;

import java.util.ArrayList;

import modelo.Cliente;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class DaoCliente {
	private SessionFactory fabrica;

	public DaoCliente()throws Exception
	{	fabrica=new Configuration().addClass(modelo.Cliente.class).buildSessionFactory();
		
	}
	public void cadastrar(Cliente c)throws Exception
	{
		Session sessao=fabrica.openSession();
		Transaction transacao=sessao.beginTransaction();
		sessao.save(c);
		transacao.commit();
		sessao.flush();
		sessao.close();
	}
	public Cliente consultar(Cliente c)throws Exception
	{
		Session sessao=fabrica.openSession();
		Transaction transacao=sessao.beginTransaction();
		c=(Cliente)sessao.get(modelo.Cliente.class,c.getNome_cli());
		
		transacao.commit();
		sessao.flush();
		sessao.close();
		return c;
	}
	public Cliente consultarCNPJ(Cliente c)throws Exception
	{
		Cliente cli = null;
		Session sessao=fabrica.openSession();
		Transaction transacao=sessao.beginTransaction();
		Query q=sessao.createQuery("from modelo.Cliente " + "where cnpj_cli = '" + c.getCnpj_cli() + "'");
		cli = (Cliente) q.uniqueResult();		
		transacao.commit();
		sessao.flush();
		sessao.close();
		return cli;
	}
	public Cliente consultar(int id)throws Exception
	{		
		Cliente cli = null;
		Session sessao=fabrica.openSession();
		Transaction transacao=sessao.beginTransaction();
		Query q=sessao.createQuery("from modelo.Cliente " + "where id_cliente = " + id);
		cli = (Cliente) q.uniqueResult();		
		transacao.commit();
		sessao.flush();
		sessao.close();
		return cli;
	}
	public void excluir(Cliente c)throws Exception
	{
		Session sessao=fabrica.openSession();
		Transaction transacao=sessao.beginTransaction();
		sessao.delete(c);
		transacao.commit();
		sessao.flush();
		sessao.close();
	}
	public void alterar(Cliente c)throws Exception
	{
		Session sessao=fabrica.openSession();
		Transaction transacao=sessao.beginTransaction();
		sessao.update(c);
		transacao.commit();
		sessao.flush();
		sessao.close();
	}
	public ArrayList<Cliente> consultarTodos(){
		Session sessao=fabrica.openSession();
		Transaction transacao=sessao.beginTransaction();
		Query q=sessao.createQuery("from modelo.Cliente");
		ArrayList<Cliente> clientes=(ArrayList<Cliente>)q.list();
		transacao.commit();
		sessao.flush();
		sessao.close();
		return clientes;
	}
	
	public ArrayList<Cliente> consultarTodosNome(String nome){
		Session sessao=fabrica.openSession();
		Transaction transacao=sessao.beginTransaction();
		Query q=sessao.createQuery("from modelo.Cliente where nome_cli like '%" + nome + "%' order by nome_cli");
		ArrayList<Cliente> clientes=(ArrayList<Cliente>)q.list();
		transacao.commit();
		sessao.flush();
		sessao.close();
		return clientes;
	}
	

}
